package com.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.common.R;
import com.reggie.dto.SetMealDto;
import com.reggie.entity.category;
import com.reggie.entity.setMeal;
import com.reggie.entity.setMealDish;
import com.reggie.service.categoryService;
import com.reggie.service.dishService;
import com.reggie.service.setMealDishService;
import com.reggie.service.setMealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/setmeal")
@Slf4j
@Transactional
public class setMealController {
    @Autowired
    private setMealService setMealService;

    @Autowired
    private setMealDishService setMealDishService;

    @Autowired
    private categoryService categoryService;

    @Autowired
    private dishService dishService;

    /**
     * @param meal
     * @param session
     * @return com.reggie.common.R<java.lang.String>
     * @description: 新增套餐
     * @author 86187
     * @date: 2022/11/19 16:39
     */

    @PostMapping
    public R<String> saveMeal(@RequestBody SetMealDto meal, HttpSession session) {
        System.out.println(meal);
        boolean flag1 = setMealService.save(meal);
        List<setMealDish> setmealDishes = meal.getSetmealDishes();
        setmealDishes.forEach(t -> {
            t.setSetmealId(meal.getId() + "");
        });
        boolean flag2 = setMealDishService.saveBatch(setmealDishes);
        if (flag1 && flag2) {
            log.info("{}:创建了套餐", session.getAttribute("employee"));
            return R.success("新增套餐成功!");
        }
        return R.success("新增套餐失败!");
    }

    /**
     * @param page
     * @param pageSize
     * @param name
     * @return com.reggie.common.R<com.baomidou.mybatisplus.extension.plugins.pagination.Page>
     * @description: 实现分页查询套餐
     * @author 86187
     * @date: 2022/11/20 9:39
     */

    @GetMapping("/page")
    public R<Page> selectMealList(int page, int pageSize, String name) {
        Page<setMeal> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<setMeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, setMeal::getName, name);
        setMealService.page(pageInfo, queryWrapper);
        if (pageInfo.getRecords() != null) {
            List<SetMealDto> DtoList = new ArrayList<>();
            List<setMeal> records = pageInfo.getRecords();
            records.forEach(t -> {
                SetMealDto setMealDto = new SetMealDto();
                BeanUtils.copyProperties(t, setMealDto);
                category category = categoryService.getById(t.getCategoryId());
                setMealDto.setCategoryName(category.getName());
                DtoList.add(setMealDto);
            });
            Page<SetMealDto> setMealDtoPage = new Page<>();
            BeanUtils.copyProperties(pageInfo, setMealDtoPage, "records");
            setMealDtoPage.setRecords(DtoList);
            return R.success(setMealDtoPage);
        }
        return R.error("未查找到相应的数据");
    }

    /**
     * @param status
     * @param ids
     * @return com.reggie.common.R<java.lang.String>
     * @description: 对套餐开启启售和停售
     * @author 86187
     * @date: 2022/11/20 9:38
     */

    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable("status") Integer status, @RequestParam(value = "ids", required = true) Long[] ids) {
        LambdaQueryWrapper<setMeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ids != null, setMeal::getId, ids);
        setMeal setMeal = new setMeal();
        setMeal.setStatus(status);
        boolean update = setMealService.update(setMeal, queryWrapper);
        if (update) {
            log.info("{}:进行售卖状态更改", ids);
            return R.success(status == 1 ? "启售成功!" : "停售成功!");
        }
        log.error("{}:售卖状态更改失败", ids);
        return R.error(status == 1 ? "启售失败!" : "停售失败!");
    }

    /**
     * @param ids
     * @return com.reggie.common.R<java.lang.String>
     * @description: 删除套餐及其相应的菜品
     * @author 86187
     * @date: 2022/11/20 10:19
     */

    @DeleteMapping()
    public R<String> deleteMeal(@RequestParam(value = "ids", required = false) Long[] ids) {
        LambdaQueryWrapper<setMeal> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<setMealDish> mealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ids != null, setMeal::getId, ids);
        mealDishLambdaQueryWrapper.in(ids != null, setMealDish::getSetmealId, ids);
        boolean remove1 = setMealService.remove(queryWrapper);
        boolean remove2 = setMealDishService.remove(mealDishLambdaQueryWrapper);
        if (remove1 && remove2) {
            log.info("{}:成功删除!", ids);
            return R.success("删除套餐成功!");
        }
        log.info("{}:删除失败!", ids);
        return R.error("系统繁忙,删除套餐失败!");
    }

    /**
     * @param id
     * @return com.reggie.common.R<com.reggie.dto.SetMealDto>
     * @description: 获取套餐信息，进行修改
     * @author 86187
     * @date: 2022/11/20 10:30
     */

    @GetMapping("/{id}")
    public R<SetMealDto> getSetMealById(@PathVariable("id") Long id) {
        LambdaQueryWrapper<setMeal> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<setMealDish> mealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(id != null, setMeal::getId, id);
        mealDishLambdaQueryWrapper.eq(id != null, setMealDish::getSetmealId, id);
        //获取套餐
        setMeal meal = setMealService.getOne(queryWrapper);
        //获取套餐对应的菜品
        List<setMealDish> list = setMealDishService.list(mealDishLambdaQueryWrapper);
        SetMealDto setMealDto = new SetMealDto();
        BeanUtils.copyProperties(meal, setMealDto);
        //将对应的菜品传递给SetMealDto
        setMealDto.setSetmealDishes(list);
        return R.success(setMealDto);
    }

    /**
     * @param setMealDto
     * @return com.reggie.common.R<java.lang.String>
     * @description: 保存修改的套餐信息
     * @author 86187
     * @date: 2022/11/20 11:18
     */

    @PutMapping()
    public R<String> saveUpdateMeal(@RequestBody SetMealDto setMealDto) {
        LambdaQueryWrapper<setMeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setMealDto.getId() != null, setMeal::getId, setMealDto.getId());
        LambdaQueryWrapper<setMealDish> setMealDishWrapper = new LambdaQueryWrapper<>();
        setMealDishWrapper.eq(setMealDto.getId() != null, setMealDish::getSetmealId, setMealDto.getId());
        setMeal setMeal = new setMeal();
        BeanUtils.copyProperties(setMealDto, setMeal, "categoryName", "copies", "setmealDishes");
        boolean flag = setMealService.update(setMeal, queryWrapper);
        //删除之前的信息，保存新的信息
        boolean saveBatchFlag = true;
        if (setMealDto.getSetmealDishes().size() != 0) {
            boolean removeFlag = setMealDishService.remove(setMealDishWrapper);
            setMealDto.getSetmealDishes().forEach(t -> {
                t.setSetmealId(setMealDto.getId() + "");
            });
            saveBatchFlag = setMealDishService.saveBatch(setMealDto.getSetmealDishes());
        }
        if (flag && saveBatchFlag) {
            log.info("{}:套餐修改成功", setMealDto.getId());
            return R.success("修改成功!");
        }
        return R.error("系统繁忙，修改失败!");
    }

    /**
     * @param categoryId
     * @param status
     * @return com.reggie.common.R<java.util.List < com.reggie.entity.dish>>
     * @description: 返回套餐列表给app前端
     * @author 86187
     * @date: 2022/11/22 22:12
     */

    @GetMapping("/list")
    public R<List<SetMealDto>> selectMealListForFront(@RequestParam(value = "categoryId") Long categoryId, @RequestParam(value = "status") Integer status) {
        LambdaQueryWrapper<setMeal> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<setMealDish> mealQueryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(categoryId != null, setMeal::getCategoryId, categoryId);
        queryWrapper.eq(status != null, setMeal::getStatus, status);
        List<setMeal> list = setMealService.list(queryWrapper);
        List<SetMealDto> setMealDtoList = new ArrayList<>();
        list.forEach(t -> {
            SetMealDto setMealDto = new SetMealDto();
            BeanUtils.copyProperties(t, setMealDto);
            List<setMealDish> mealDishList = setMealDishService.list(mealQueryWrapper.eq(t.getId() != null, setMealDish::getSetmealId, t.getId()));
            setMealDto.setSetmealDishes(mealDishList);
            setMealDtoList.add(setMealDto);
        });
        return R.success(setMealDtoList);
    }
}
